<template>
  <div style="width: 100%;height: 100%;">
    <BaseMainSlot :show-tab="true">
      <template v-slot:search-box>
        <SearchForm :form-config="formConfig" :form-data="filterData" @search="search" />
      </template>
      <template v-slot:tab-select>
        <SelectButton :buttonselectlist="buttonselectlist" @nowselectbuttonindex="batchstaumet" />
      </template>
      <template v-slot:btn-box>
        <div class="page-top__todo">
          <CommonBtn @click="reload">刷新</CommonBtn>
        </div>
      </template>
      <template v-slot:table-box>
        <tdtable v-loading="tableLoading" :page="page" :prop-list="propList" :table-data="tableData" :show-index-column="true" :show-select-column="true" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" @handleSelectionChange="handleSelectionChange">
          <template v-slot:productName="{ row }">
            <span v-if="row.taskId">{{ row.product.productName }}</span>
          </template>
          <template v-slot:processingVolume="{ row }">
            <span v-if="row.processingVolume">{{ row.processingVolume }} {{ row.product.unitName }}</span>
          </template>
          <template v-slot:actualProcessingVolume="{ row }">
            <span v-if="row.actualProcessingVolume">{{ row.actualProcessingVolume }} {{ row.product.unitName }}</span>
          </template>
          <template v-slot:equment="{ row }">
            <el-button v-if="row.taskId" type="text" class="text-btn-cursor" size="small" @click="showEqu(row)">查看</el-button>
          </template>
          <template v-slot:sop="{ row }">
            <el-button v-if="row.taskId" type="text" class="text-btn-cursor" size="small" @click="showSop(row)">下载</el-button>
          </template>
          <template v-slot:time="{ row }">
            <span v-if="row.taskId">{{ row.startTime | formateTime }}--{{ row.endTime | formateTime }}</span>
          </template>
          <template v-slot:actTime="{ row }">
            <span v-if="row.taskId">{{ row.actualStartTime | formateTime }}--{{ row.actualEndTime | formateTime }}</span>
          </template>
          <template v-slot:suspendEndTime="{ row }">
            <span v-if="row.taskId">{{ row.suspendEndTime | formateTime }}</span>
          </template>
          <template v-slot:expectMaterial="{ row }">
            <el-button v-if="row.taskId" type="text" class="text-btn-cursor" size="small" @click="showMaterial(row)">查看</el-button>
          </template>
          <template v-slot:pickingDetail="{ row }">
            <el-button v-if="row.taskId" type="text" class="text-btn-cursor" size="small" @click="showInventory(row)">查看</el-button>
          </template>
          <template v-slot:suspendReason="{ row }">
            <el-button v-if="row.taskId" type="text" class="text-btn-cursor" size="small" @click="showAbort(row)">查看</el-button>
          </template>
          <template v-slot:progress="{ row }">
            <el-button v-if="row.taskId" type="text" class="text-btn-cursor" size="small" @click="showTaskProcess(row)">查看</el-button>
          </template>
          <template v-slot:overdue="{ row }">
            <span v-if="row.taskId">{{ row.overdue ? '是' : '否' }}</span>
          </template>
          <template v-slot:edit="{ row }">
            <div v-if="row.batchId" class="operate">
              <template v-if="row.status === 'CREATE'">
                <el-button type="text" class="text-btn-cursor" size="small" @click="edit(row)">修改</el-button>
                <el-button type="text" class="text-btn-cursor" size="small" @click="startTask(row)">开始</el-button>
                <el-button type="text" class="text-btn-cursor cursor-delete" size="small" @click="handleDelete(row.taskId)">删除</el-button>
              </template>
              <el-button v-if="row.status === 'PICKING'" type="text" class="text-btn-cursor" size="small" @click="pickingTask(row)">领料</el-button>
              <el-button v-if="row.status === 'ASSIGNED'" type="text" class="text-btn-cursor" size="small" @click="startJobTask(row)">开始作业</el-button>
              <template v-if="row.status === 'PROGRESS'">
                <el-button type="text" class="text-btn-cursor" size="small" @click="updateTask(row)">上报</el-button>
                <el-button type="text" class="text-btn-cursor" size="small" @click="done(row, 'done')">完成</el-button>
                <el-button type="text" class="text-btn-cursor" size="small" @click="done(row, 'abort')">中止</el-button>
                <el-button type="text" class="text-btn-cursor" size="small" @click="sup(row)">补领料</el-button>
              </template>
              <template v-if="['COMPLETED', 'SUSPENDED'].includes(row.status)">
                <el-button type="text" class="text-btn-cursor" size="small" @click="generateReceipt(row)">生成入库单</el-button>
              </template>
            </div>
          </template>
        </tdtable>
      </template>
    </BaseMainSlot>
    <AddEditDialog v-model="addEditShow" :selected-item="selectedItem" :person-list="personList" :product-list="productList" :product-line-list="productLineList" :batch-list="batchList" @reflash="search" />
    <el-dialog title="上报作业进度" :visible.sync="showUpdateDialog" top="0" :close-on-click-modal="false" @close="showUpdateDialog = false">
      <el-form v-if="selectedItem !== null" ref="form" :model="formData" class="el-form report-form">
        <el-form-item label="当前已完成的加工量：" prop="num" class="w100p" :rules="[{ required: true, message: '请输入当前已完成的加工量' }]">
          <div class="input-group">
            <el-input-number :precision="0" v-model="formData.num" type="number" :min="0" placeholder="请输入当前已完成的加工量" clearable />
            <div class="el-input-group__append">{{ selectedItem.product.unitName }}</div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="showUpdateDialog = false">取 消</el-button>
        <el-button :loading="saveLoading" type="primary" class="savebtn" @click="report">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="中止原因" :visible.sync="showAbortDialog" top="0" :close-on-click-modal="false" @close="showAbortDialog = false">
      <p v-if="selectedItem != null">{{ selectedItem.suspendReason || '' }}</p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="savebtn" @click="showAbortDialog = false">关 闭</el-button>
      </div>
    </el-dialog>
    <MaterialExp v-model="showMaterialList" :list="materialList" title="原料预期" />
    <Equ v-model="showEquDialog" :list="currentDataEquList" title="加工设备" />
    <SopFile v-model="showProcess" :selected-item="selectedProductItem" @reflash="search" />
    <Done v-model="showToDone" :selected-item="selectedItem" :type="doneType" @reflash="search" />
    <Supplement v-model="showSup" :selected-item="selectedItem" @reflash="search" />
    <Process v-model="showTaskProcessDia" :selected-item="selectedItem" />
    <Inventory v-model="showInventoryDia" :selected-item="selectedItem" />
  </div>
</template>
<script>
import BaseMainSlot from '@/components/BaseMainSlot/newBaseMainSlot';
import SearchForm from '@/components/searchForm';
import apiProduct from '@/api/processing-management/basic-info-manage/product-process';
import apiProductLine from '@/api/processing-management/basic-info-manage/product-line';
import apiBatch from '@/api/processing-management/process-batch-manage/process-batch-creation/index';
import processTaskApi from '@/api/processing-management/process-management/processing-task';
import api from '@/api/processing-management/process-task-manage/index';
import tdtable from '@/components/table/index.vue';
import SopFile from '../creation/components/sop-file.vue';
import SelectButton from '@/components/selectbutton/index.vue';
import AddEditDialog from '../creation/components/add-edit-dialog.vue';
import Done from './components/done.vue';
import Supplement from './components/supplement.vue';
import Process from './components/process.vue';
import Inventory from './components/inventory.vue';
import { getToken } from '@/utils/auth';
import moment from 'moment';
import Equ from '@/views/processing-management/basic-info-manage/product-line/components/equ.vue';
import MaterialExp from '@/views/processing-management/process-batch-manage/process-batch-creation/components/material-exp.vue';
export default {
  inject: ['reload'],
  components: {
    BaseMainSlot,
    SearchForm,
    tdtable,
    SopFile,
    SelectButton,
    AddEditDialog,
    Done,
    Supplement,
    Process,
    Inventory,
    Equ,
    MaterialExp
  },
  filters: {
    formateTime: function(value) {
      return moment(value).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  props: {},
  data() {
    return {
      showInventoryDia: false,
      showAbortDialog: false,
      showTaskProcessDia: false,
      showSup: false,
      saveLoading: false,
      formData: {
        num: ''
      },
      buttonselectlist: [
        { name: '待开始', status: 'CREATE' },
        { name: '待领料', status: 'PICKING' },
        { name: '待作业', status: 'ASSIGNED' },
        { name: '作业中', status: 'PROGRESS' },
        { name: '已完成', status: 'COMPLETED' },
        { name: '已中止', status: 'SUSPENDED' }
      ],
      curTabIndex: 0,
      curStatus: null,
      currentDataEquList: [],
      showEquDialog: false,
      showMaterialList: false,
      materialList: [],
      tableData: [],
      tableLoading: false,
      currentPage: 1,
      pageSize: 10,
      totalSize: 0,
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      formConfig: [
        {
          label: '加工作业名称',
          prop: 'taskName',
          type: 'input'
        },
        {
          label: '加工批次名称',
          prop: 'batchName',
          type: 'input'
        },
        {
          label: '加工产品',
          prop: 'productId',
          type: 'select',
          options: [],
          optionKey: { label: 'productName', value: 'productId' }
        },
        {
          label: '加工产线',
          prop: 'productLineId',
          type: 'select',
          options: [],
          optionKey: { label: 'productLineName', value: 'productLineId' }
        },
        {
          label: '加工批次号',
          prop: 'batchNo',
          type: 'input'
        },
        {
          label: '预期加工时间',
          prop: 'date',
          type: 'daterange'
        }
      ],
      filterData: {},
      addEditShow: false,
      selectedList: [],
      delActive: false,
      selectedItem: null,
      productList: [],
      productLineList: [],
      batchList: [],
      personList: [],
      propList: [],
      propListOrg: [
        { prop: 'taskName', label: '加工作业名称', minWidth: '150' },
        { prop: 'batchNo', label: '关联批次号', minWidth: '100' },
        { prop: 'productName', label: '加工产品', minWidth: '150', slotName: 'productName' },
        { prop: 'productLineName', label: '加工产线', minWidth: '100' },
        {
          prop: 'processingVolume',
          label: '预期加工量',
          minWidth: '100',
          slotName: 'processingVolume'
        },
        {
          prop: 'actualProcessingVolume',
          label: '实际加工量',
          minWidth: '100',
          slotName: 'actualProcessingVolume'
        },
        {
          prop: 'progress',
          label: '加工进度记录',
          minWidth: '150',
          slotName: 'progress'
        },
        { prop: 'equment', label: '加工设备', minWidth: '100', slotName: 'equment' },
        { prop: 'sop', label: '工序SOP文件', minWidth: '150', slotName: 'sop' },
        { prop: 'overdue', label: '是否逾期', minWidth: '150', slotName: 'overdue' },
        { prop: 'processName', label: '处理人', minWidth: '150' },
        {
          prop: 'time',
          label: '预期工期',
          minWidth: '260',
          slotName: 'time'
        },
        {
          prop: 'actTime',
          label: '实际工期',
          minWidth: '260',
          slotName: 'actTime'
        },
        {
          prop: 'expectMaterial',
          label: '原料预期',
          minWidth: '100',
          slotName: 'expectMaterial'
        },
        {
          prop: 'suspendEndTime',
          label: '中止时间',
          minWidth: '200',
          slotName: 'suspendEndTime'
        },
        {
          prop: 'suspendReason',
          label: '中止原因',
          minWidth: '100',
          slotName: 'suspendReason'
        },
        {
          prop: 'pickingDetail',
          label: '领料详情',
          minWidth: '100',
          slotName: 'pickingDetail'
        },
        { label: '操作', minWidth: '200', slotName: 'edit' }
      ],
      showProcess: false,
      selectedProductItem: null,
      showUpdateDialog: false,
      rules: {
        num: [
          {
            required: true,
            message: '请输入当前已完成的加工量'
          }
        ]
      },
      showToDone: false,
      doneType: 'done'
    };
  },
  watch: {
    addEditShow(v) {
      if (!v) {
        setTimeout(() => {
          this.selectedItem = null;
        }, 250);
      }
    },
    showUpdateDialog(v) {
      if (!v) {
        setTimeout(() => {
          this.$refs.form.resetFields();
          this.selectedItem = null;
        }, 250);
      }
    },
    showToDone(v) {
      if (!v) {
        setTimeout(() => {
          this.selectedItem = null;
        }, 250);
      }
    }
  },
  created() {
    this.getProductList();
    this.getProductListLine();
    this.getBatchList();
    this.getPersonOptions();
    this.search();
  },
  mounted() {},
  methods: {
    getProductList() {
      apiProduct.queryByCondition({ status: 1 }).then(res => {
        if (res.code === 1) {
          this.productList = res.data;
          this.formConfig.find(i => i.prop === 'productId').options = res.data;
        }
      });
    },
    getProductListLine() {
      apiProductLine.queryByCondition({}).then(res => {
        if (res.code === 1) {
          this.productLineList = res.data;
          this.formConfig.find(i => i.prop === 'productLineId').options = res.data;
        }
      });
    },
    getBatchList() {
      apiBatch.queryByCondition({ statusList: ['CREATE', 'TOWARD'] }).then(res => {
        if (res.code === 1) {
          this.batchList = res.data;
        }
      });
    },
    getPersonOptions() {
      processTaskApi.personQuery().then(res => {
        if (res.code === 1) {
          this.personList = res.data;
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedList = list.map(item => {
        return item.taskId;
      });
      if (this.selectedList && this.selectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    handleSizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.search();
    },
    handleCurrentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.search();
    },
    search() {
      const { buttonselectlist, curTabIndex } = this;
      const { currentPage, pageSize } = this.page;
      const filterData = JSON.parse(JSON.stringify(this.filterData));
      if (filterData.date && filterData.date.length !== 0) {
        filterData.startTime = this.$moment(filterData.date[0]).format('YYYY-MM-DD HH:mm:ss');
        filterData.endTime = this.$moment(filterData.date[1]).format('YYYY-MM-DD HH:mm:ss');
      }
      delete filterData.date;
      filterData.status = buttonselectlist[curTabIndex].status;
      this.tableLoading = true;
      api
        .queryPageByCondition({
          page: currentPage,
          size: pageSize,
          entity: {
            status: 'CREATE',
            ...filterData
          }
        })
        .then(res => {
          if (res.code === 1) {
            this.tableData = this.$utils.addblankmet(res.data.content, pageSize);
            this.page.total = res.data.totalElements;
            if (res.data.content.length === 0 && this.page.currentPage !== 1) {
              this.page.currentPage--;
              this.search();
            }
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    edit(item) {
      this.selectedItem = JSON.parse(JSON.stringify(item));
      this.addEditShow = true;
    },
    del() {
      this.handleDelete(this.selectedList);
    },
    handleDelete(no) {
      let list = [no];
      if (no instanceof Array) {
        list = no;
      }
      this.$confirm('是否确认删除？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonClass: 'btnFalses',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      })
        .then(() => {
          api.delListByIdList({ taskIdList: list }).then(res => {
            if (res.code === 1) {
              this.$message.success('删除成功');
              this.search();
            } else {
              this.$message.error('删除失败');
            }
          });
        })
        .catch(_ => {});
    },
    updateSelectedItem(item) {
      this.selectedItem = item;
    },
    showMaterial(row) {
      this.materialList = row.taskRawMaterialList;
      this.showMaterialList = true;
    },
    queryBomByProduct(row) {
      const { processingVolume, productId } = row;
      if (processingVolume && productId) {
        api.queryBomByProduct(processingVolume, productId).then(res => {
          if (res.code === 1) {
            this.materialList = res.data;
          }
        });
      }
    },
    showEqu(item) {
      this.currentDataEquList = item.equipmentList;
      this.showEquDialog = true;
    },
    showSop(item) {
      this.selectedProductItem = item.product;
      this.showProcess = true;
    },
    getProcess(productId) {
      this.processLoading = true;
      apiProduct
        .getProcessesListByCond({
          productId
        })
        .then(res => {
          if (res.code === 1) {
            this.processList = res.data;
          }
        })
        .finally(() => {
          this.processLoading = false;
        });
    },
    startTask(row) {
      this.$confirm('是否确认开始？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonClass: 'btnFalses',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          api.startTask(row.taskId).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            }
          });
        })
        .catch(_ => {});
    },
    pickingTask(row) {
      this.$confirm('是否确认生成领料单？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonClass: 'btnFalses',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          api.pickingTask(row.taskId).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            }
          });
        })
        .catch(_ => {});
    },
    startJobTask(row) {
      this.$confirm('确认已领到加工原料，并开始进行加工作业吗？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonClass: 'btnFalses',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          api.startJobTask(row.taskId).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            }
          });
        })
        .catch(_ => {});
    },
    generateReceipt(row) {
      this.$confirm('确定要生成所有产品入库单和原料退库单吗？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonClass: 'btnFalses',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          api.generateReceipt(row.taskId).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            }
          });
        })
        .catch(_ => {});
    },
    batchstaumet(index) {
      this.curTabIndex = index;
      this.curStatus = this.buttonselectlist[this.curTabIndex];
      this.setPropList();
      this.handleCurrentChange(1);
    },
    // 待开始，待领料，待作业，作业中，已完成，已中止）,可用值:CREATE,PICKING,ASSIGNED,PROGRESS,COMPLETED,SUSPENDED
    setPropList() {
      const { propListOrg } = this;
      const { status } = this.curStatus;
      if (status === 'CREATE') {
        this.propList = propListOrg.filter(item => !['pickingDetail', 'progress', 'overdue', 'actualProcessingVolume', 'suspendEndTime', 'suspendReason', 'actTime'].includes(item.prop));
      }
      if (status === 'PICKING') {
        this.propList = propListOrg.filter(item => !['expectMaterial', 'progress', 'overdue', 'actualProcessingVolume', 'suspendEndTime', 'suspendReason', 'actTime'].includes(item.prop));
      }
      if (status === 'ASSIGNED') {
        this.propList = propListOrg.filter(item => !['expectMaterial', 'progress', 'overdue', 'actualProcessingVolume', 'suspendEndTime', 'suspendReason', 'actTime'].includes(item.prop));
      }
      if (status === 'PROGRESS') {
        this.propList = propListOrg.filter(item => !['expectMaterial', 'actualProcessingVolume', 'suspendEndTime', 'suspendReason', 'actTime', 'equment'].includes(item.prop));
      }
      if (status === 'COMPLETED') {
        this.propList = propListOrg.filter(item => !['expectMaterial', 'processingVolume', 'suspendEndTime', 'suspendReason', 'equment', 'time'].includes(item.prop));
      }
      if (status === 'SUSPENDED') {
        this.propList = propListOrg.filter(item => !['expectMaterial', 'processingVolume', 'actTime', 'equment', 'overdue', 'time'].includes(item.prop));
      }
    },
    // 上报
    updateTask(row) {
      this.selectedItem = JSON.parse(JSON.stringify(row));
      this.showUpdateDialog = true;
    },
    report() {
      const { formData, selectedItem } = this;
      const paylod = JSON.parse(JSON.stringify(formData));
      this.$refs['form'].validate(async valid => {
        if (valid) {
          paylod.personNo = getToken('personNo');
          paylod.name = getToken('username');
          paylod.taskId = selectedItem.taskId;
          this.$confirm('是否确认上报？', '提示', {
            distinguishCancelAndClose: true,
            confirmButtonClass: 'btnFalses',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          })
            .then(() => {
              this.saveLoading = true;
              api
                .reportTask(paylod)
                .then(res => {
                  if (res.code === 1) {
                    this.$message.success(res.msg);
                    this.showUpdateDialog = false;
                    this.search();
                  }
                })
                .finally(_ => {
                  this.saveLoading = false;
                });
            })
            .catch(_ => {});
        }
      });
    },
    done(row, type) {
      this.selectedItem = JSON.parse(JSON.stringify(row));
      this.doneType = type;
      this.showToDone = true;
    },
    sup(row) {
      this.selectedItem = JSON.parse(JSON.stringify(row));
      this.showSup = true;
    },
    showTaskProcess(row) {
      this.selectedItem = JSON.parse(JSON.stringify(row));
      this.showTaskProcessDia = true;
    },
    showAbort(row) {
      this.selectedItem = JSON.parse(JSON.stringify(row));
      this.showAbortDialog = true;
    },
    showInventory(row) {
      this.selectedItem = JSON.parse(JSON.stringify(row));
      this.showInventoryDia = true;
    }
  }
};
</script>
<style lang="scss" scoped>
.input-group {
  display: flex;
  align-items: center;
  width: 100%;
  > * {
    &:first-of-type {
      flex: 0 0 80%;
    }
  }
  .el-input-group__append {
    width: 100%;
    text-align: center;
    height: 100%;
  }
}
.content-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
}
::v-deep .report-form .el-form-item__label {
  min-width: 200px !important;
}
</style>
